import { Collaboration_APP, TEST_NUMBER, Service_APP, TEST_INFO_NUMBER, YY_NUMBER } from '../../../public/js/config/config.js';
import { MESSAGE_SUCCESS_TYPE_001 } from '../common/pointentrance.js';
import WxcodeApi from '../../../public/js/common/api/account/wxcode.api.js';
Utils.NameSpace('SN.H5.Account.Register');
const regexp = {
    TEL: /^1[3456789]\d{9}$/,
    ID_CORD: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
    PHONE_CODE: /^[0-9]*$/,
};
let query = Utils.ParsingUrl(window.location);

/**
 *@file注册
 *@Date :2022-02-17 14:34:16
 *@create丁平
 */
(function (window, document, $) {
    let _timer;
    $(function () {
        /*JS严格模式*/
        'use strict';
        $('body').attr('data-weui-theme', 'light');
        $('#cbAgree').prop('checked', false); /*复选框默认不勾选*/
        $('input').attr('onkeyup', "this.value=this.value.replace(/[, ]/g,'')"); /*自动消除空格*/

        //if (Utils.IsNotNull(query.openId)) {
        //	SN.H5.Account.Register.AgreeClick();
        //	SN.H5.Account.Register.btnWxUserClick();//获取微信用户openId信息
        //      } else {
        SN.H5.Account.Register.userQuery();
        //}
        _decomposition();
        SN.H5.Account.Register.AgreeClick();
        SN.H5.Account.Register.AddUserClick();
        SN.H5.Account.Register.GetCodeSubmit();

        //SN.H5.Account.Register.GetVerification();
    });

    //获取微信用户openId信息
    SN.H5.Account.Register.btnWxUserClick = function () {
        $.ajax({
            url: Utils.CurDomain.AccountUrl + `/mpaccounts/register/${Utils.GetQueryString('state')}/${query.openId}`, //获取code关联用户的JWT信息
            type: 'GET',
            success: function (res) {
                let result = JSON.parse(res);
                $('#headImgurl').attr('src', result.headimgurl);
                $('#userNickName').text(result.nickName);
                $('#openId').val(query.openId);
                $('#headimgurlContent').val(result.headimgurl);

                $('#iptTrueName').val(result.trueName);
                $('#phoneNum').val(result.phoneNum);
                $('#numCode').val(result?.numCode);
                $('#idCardNum').val(result?.idCardNum);
                $('#remark').val(result.remark);
                $('#btnAddWXUser').text(`修改`);
            },
            error: Utils.AjaxError,
        });
    };

    //获取验证码
    SN.H5.Account.Register.GetVerification = function () {
        //获取guid
        $.ajax({
            url: Utils.CurDomain.AccountUrl + '/accounts/guid',
            type: 'GET',
            success: function (result) {
                if (result.isSucceed) {
                    let guid = result.data;
                    $('#vcode').attr('src', Utils.CurDomain.AccountUrl + '/accounts/checkcode?vcguid=' + guid);
                } else {
                    toastr.error('error');
                }
            },
            error: function (e) {
                console.error(e);
            },
        });
    };

    //网页端授权获取微信用户详情
    SN.H5.Account.Register.userQuery = function () {
        let wxCode = Utils.GetQueryString('code');
        let wxState = Utils.GetQueryString('state');
        $.ajax({
            url: Utils.CurDomain.WeiXinUrl + '/wxauths/user/code',
            type: 'GET',
            timeout: 3000,
            data: {
                code: wxCode,
                SId: wxState,
            },
            success: function (res) {
                $('#headImgurl').attr('src', res.data.headimgurl);
                $('#userNickName').text(res.data.nickname);
                $('#openId').val(res.data.openid);
                $('#headimgurlContent').val(res.data.headimgurl);
            },
            error: Utils.AjaxError,
        });
    };

    //TODO : 判断是信息服务还是IT服务
    //Date :2022-02-17 14:51:48
    //create丁平
    const _decomposition = () => {
        let _state = Utils.ParsingUrl(window.location);
        // $('#work-no').remove();
        // 		$('#itmp-card').remove();
        // 		$('#info-card').show();
        // 		$('#it-agreement').empty().append(`<a href="javaScript:" style="color:#3e8ef7">《神农用户条款》</a><a href="javaScript:" style="color:#3e8ef7">《神农隐私协议》</a>`)
        // 		document.title = "登记信息";
        // 		$('#btnAddWXUser').text('登记');
        // 		return
        switch (_state.state) {
            case Collaboration_APP.sourceID: //IT 正式
                $('#info-card').remove();
                $('#it-agreement').empty().append(`<a href="../clause.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农用户条款》</a><a href="../privacy.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农隐私协议》</a>`);
                break;
            case TEST_INFO_NUMBER.sourceID: //Info测试号
                $('#work-no').remove();
                $('#itmp-card').remove();
                $('#info-card').show();
                $('#it-agreement').empty().append(`<a href="../clause.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农用户条款》</a><a href="../privacyinfo.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农隐私协议》</a>`);
                document.title = '登记信息';
                $('#btnAddWXUser').text('登记');
                break;
            case YY_NUMBER.sourceID: //IT 测试
                $('#info-card').remove();
                $('#it-agreement').empty().append(`<a href="../clause.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农用户条款》</a><a href="../privacy.html?v=${Utils.GetTime()}" style="color:#3e8ef7">《神农隐私协议》</a>`);
                break;
        }

        //输入文本后自动将字母转为大写
        $(document).on('input propertychange', '#idCardNum-info', function () {
            let capital = $(this).val();
            capital = capital.toUpperCase();
            $('#idCardNum-info').val(capital);
        });
        $(document).on('input propertychange', '#idCardNum', function () {
            let card = $(this).val();
            card = card.toUpperCase();
            $('#idCardNum').val(card);
        });
    };

    /*条款选项框单击*/
    SN.H5.Account.Register.AgreeClick = function () {
        $('#cbAgree').on('click', function (e) {
            const $btnSubmit = $('#btnAddWXUser');
            if (this.checked) {
                $btnSubmit.removeClass('weui-btn_disabled');
                $btnSubmit.removeAttr('disabled');
            } else {
                $btnSubmit.addClass('weui-btn_disabled');
                $btnSubmit.attr('disabled');
            }
        });
    };

    /*提交单击*/
    SN.H5.Account.Register.AddUserClick = function () {
        $('#btnAddWXUser').on('click', function (e) {
            if ($(this).hasClass('weui-btn_disabled')) {
                /*如果按钮为灰色阻止A标签事件*/
                e.stopPropagation();
                e.preventDefault();
                return;
            }

            SN.H5.Account.Register.UserInfoSubmit();

            /*防止多次点击*/
            $(this).css('pointer-events', 'none');
            setTimeout(function () {
                $('#btnAddWXUser').css('pointer-events', 'auto');
            }, 1500);
        });
    };

    /*用户提交*/
    SN.H5.Account.Register.UserInfoSubmit = function () {
        weui.form.validate(
            '#register-form',
            function (error) {
                if (!error) {
                    let _state = Utils.ParsingUrl(window.location);
                    let json = {
                        code: Utils.GetQueryString('code'),
                        trueName: $('#iptTrueName').val(),
                        idCardNum: _state.state == YY_NUMBER.sourceID ? $('#idCardNum').val() : $('#idCardNum-info').val(),
                        numCode: $('#numCode').val(),
                        phoneNum: $('#phoneNum').val(),
                        remark: $('#remark').val(),
                        vefctCode: $('#iptVefctCode').val(),
                        nickName: $(`#userNickName`).text(),
                        headimgurl: $(`#headimgurlContent`).val(),
                    };
                    WxcodeApi.registerWechat({
                        openId: $('#openId').val(),
                        sourceID: Utils.GetQueryString('state'),
                        infos: JSON.stringify(json),
                    }).then((res) => {
                        weui.toast(`微信用户${$('#iptTrueName').val()}注册成功`, 3000);
                        window.location.href = `../components/wait/wait.html?index=3&type=${MESSAGE_SUCCESS_TYPE_001}&state=${Utils.GetQueryString('state')}&openId=${_state.openId}`;
                    });
                }
            },
            {
                regexp: regexp,
            },
        );
    };

    //TODO : 发送验证嘛
    //Date :2022-02-21 10:24:44
    //create丁平
    SN.H5.Account.Register.GetCodeSubmit = function () {
        const phoneReg = /^1[3456789]\d{9}$/;
        $('#btnGetCode').on('click', function () {
            let phone = $('#phoneNum').val();
            if (!phoneReg.test(phone)) {
                return $.toptip('您输入的手机号码无效', 'warning');
            }
            WxcodeApi.getPhoneCode(phone).then((res) => {
                SN.H5.Account.Register.CountDown();
            });
        });
    };

    /*验证码时间*/
    SN.H5.Account.Register.CountDown = function () {
        let countdown = 60;
        if (Utils.IsNotNull(_timer)) clearInterval(_timer);
        _timer = setInterval(() => {
            if (countdown == 0) {
                $('#btnGetCode').attr('disabled', false);
                $('#btnGetCode').text('获取验证码');
                countdown = 60;
                return clearInterval(_timer);
            } else {
                $('#btnGetCode').attr('disabled', true);
                $('#btnGetCode').text('重新发送(' + countdown + ')');
                countdown--;
            }
        }, 1000);
    };
})(window, document, jQuery);
